package com.gitee.wsl.doc.prosemirror.model.node.ext

import com.gitee.wsl.doc.prosemirror.model.fragment.Fragment
import com.gitee.wsl.doc.prosemirror.model.node.Node


fun Node.closeNodeStart(openStart: Int, openEnd: Int): Node {
    val node = this
    if (openStart <= 0) return node
    var frag = node.content
    if (openStart > 1) {
        frag = frag.replaceChild(
            0,
            frag.firstChild!!.closeNodeStart(openStart - 1, if (frag.childCount == 1) openEnd - 1 else 0)
        )
    }
    if (openStart > 0) {
        frag = node.type.contentMatch.fillBefore(frag)!!.append(frag)
        if (openEnd <= 0) {
            frag = frag.append(node.type.contentMatch.matchFragment(frag)!!.fillBefore(Fragment.empty, true)!!)
        }
    }
    return node.copy(frag)
}